package com.media.system.common.utils;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 客户端工具类
 * 
 * @author Claude
 * @since 2024-01-20
 */
public class ServletUtils extends JakartaServletUtil {
    /**
     * 获取String参数
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * 获取String参数
     */
    public static String getParameter(String name, String defaultValue) {
        return convert(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name) {
        return convert(getRequest().getParameter(name), Integer.class);
    }

    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name, Integer defaultValue) {
        return convert(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获取Boolean参数
     */
    public static Boolean getParameterToBool(String name) {
        return convert(getRequest().getParameter(name), Boolean.class);
    }

    /**
     * 获取Boolean参数
     */
    public static Boolean getParameterToBool(String name, Boolean defaultValue) {
        return convert(getRequest().getParameter(name), defaultValue);
    }

    /**
     * 获得所有请求参数
     * 
     * @param request 请求对象{@link ServletRequest}
     * @return Map
     */
    public static java.util.Map<String, String[]> getParams(ServletRequest request) {
        final java.util.Map<String, String[]> map = request.getParameterMap();
        return java.util.Collections.unmodifiableMap(map);
    }

    /**
     * 获得所有请求参数
     * 
     * @param request 请求对象{@link ServletRequest}
     * @return Map
     */
    public static java.util.Map<String, String> getParamMap(ServletRequest request) {
        java.util.Map<String, String> params = new java.util.HashMap<>();
        for (java.util.Map.Entry<String, String[]> entry : getParams(request).entrySet()) {
            params.put(entry.getKey(), String.join(StringUtils.COMMA, entry.getValue()));
        }
        return params;
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        try {
            return getRequestAttributes().getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        try {
            return getRequestAttributes().getResponse();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes() {
        try {
            RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
            return (ServletRequestAttributes) attributes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将字符串渲染到客户端
     * 
     * @param response 渲染对象
     * @param string 待渲染的字符串
     */
    public static void renderString(HttpServletResponse response, String string) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否是Ajax异步请求
     * 
     * @param request HttpServletRequest
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.contains("application/json")) {
            return true;
        }

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
            return true;
        }

        String uri = request.getRequestURI();
        if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
            return true;
        }

        String ajax = request.getParameter("__ajax");
        return StringUtils.inStringIgnoreCase(ajax, "json", "xml");
    }

    /**
     * 内容编码
     * 
     * @param str 内容
     * @return 编码后的内容
     */
    public static String urlEncode(String str) {
        return URLEncoder.encode(str, StandardCharsets.UTF_8);
    }

    /**
     * 内容解码
     * 
     * @param str 内容
     * @return 解码后的内容
     */
    public static String urlDecode(String str) {
        return URLDecoder.decode(str, StandardCharsets.UTF_8);
    }

    public static <T> T convert(Object value, Class<T> targetType) {
        if (value == null) {
            return null;
        }
        if (targetType.isInstance(value)) {
            return targetType.cast(value);
        }
        String str = String.valueOf(value);
        if (targetType == String.class) {
            return targetType.cast(str);
        }
        if (targetType == Integer.class || targetType == int.class) {
            return targetType.cast(Integer.valueOf(str));
        }
        if (targetType == Boolean.class || targetType == boolean.class) {
            return targetType.cast(Boolean.valueOf(str));
        }
        throw new IllegalArgumentException("Unsupported conversion: " + targetType.getName());
    }

    public static <T> T convert(Object value, T defaultValue) {
        if (value == null) {
            return defaultValue;
        }
        @SuppressWarnings("unchecked")
        Class<T> targetType = (Class<T>) defaultValue.getClass();
        try {
            return convert(value, targetType);
        } catch (Exception e) {
            return defaultValue;
        }
    }
}